/*
 * @File name:
 * @Author: 1079161148@qq.com
 * @Version: V1.0
 * @Date: 2025-03-03 17:13:18
 * @Description:
 * Copyright (C) 2024-{year} Tsing Micro Technology Inc All rights reserved.
 */
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import OpenAI from 'openai'
import path from 'path'
import { LoremIpsum } from 'lorem-ipsum'

// 根据环境加载对应的配置文件
const envFile =
  process.env.NODE_ENV === 'production'
    ? '.env.production'
    : process.env.NODE_ENV === 'staging'
      ? '.env.staging'
      : '.env.development'

dotenv.config({ path: path.resolve(process.cwd(), envFile) })

// 验证环境变量是否正确加载
console.log('API Key:', process.env.DEEPSEEK_API_KEY ? '已配置' : '未配置')

const app = express()
const PORT = process.env.PORT || 8080
const API_KEY = process.env.DEEPSEEK_API_KEY

// 中间件配置
app.use(cors())
app.use(bodyParser.json())

// 创建 OpenAI 实例
const openai = new OpenAI({
  apiKey: API_KEY,
  baseURL: 'https://api.deepseek.com/v1',
  defaultHeaders: {
    'Content-Type': 'application/json',
  },
  defaultQuery: undefined,
  organization: undefined,
  timeout: 30000,
  httpAgent: undefined,
  maxRetries: 2,
})

// 创建 Lorem 实例
const Lorem = new LoremIpsum({
  sentencesPerParagraph: {
    max: 8,
    min: 4,
  },
  wordsPerSentence: {
    max: 16,
    min: 4,
  },
})

// 模拟用户数据
const users = [
  {
    id: 1,
    username: 'admin',
    password: '123456',
    name: '管理员',
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
  },
]

// 模拟朋友圈数据
const moments = Array.from({ length: 50 }, (_, index) => ({
  id: index + 1,
  userId: Math.floor(Math.random() * 10) + 1,
  userName: `用户${Math.floor(Math.random() * 10) + 1}`,
  avatar: `https://picsum.photos/seed/user${Math.floor(Math.random() * 10) + 1}/100`,
  content: `这是第${index + 1}条朋友圈内容，${Lorem.generateSentences(2)}`,
  images: Array.from(
    { length: Math.floor(Math.random() * 9) + 1 },
    (_, imgIndex) => `https://picsum.photos/seed/moment${index}${imgIndex}/400/400`,
  ),
  location: Math.random() > 0.5 ? '深圳市南山区' : '',
  likeCount: Math.floor(Math.random() * 100),
  commentCount: Math.floor(Math.random() * 50),
  createdAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
  isLiked: Math.random() > 0.5,
}))

// 模拟视频数据
const videoList = [
  {
    id: 1,
    title: '【直播】英雄联盟S13全球总决赛',
    cover: 'https://picsum.photos/seed/live1/400/300',
    url: 'https://vjs.zencdn.net/v/oceans.mp4',
    uploader: '英雄联盟赛事',
    avatar: 'https://picsum.photos/seed/avatar1/100/100',
    views: 2345678,
    danmaku: 23456,
    time: '2023-11-19 20:00',
    type: 'live',
    desc: 'S13全球总决赛 WBG vs T1',
    category: '游戏',
    tags: ['英雄联盟', '电子竞技', 'S13'],
    location: '上海',
  },
  {
    id: 2,
    title: '【直播】和观众一起看动漫',
    cover: 'https://picsum.photos/seed/live2/400/300',
    url: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
    uploader: '动漫老师',
    avatar: 'https://picsum.photos/seed/avatar2/100/100',
    views: 12345,
    danmaku: 1234,
    time: '2023-11-19 19:30',
    type: 'live',
    desc: '一起来看动漫吧',
    category: '动漫',
    tags: ['动漫', '二次元'],
    location: '北京',
  },
  {
    id: 3,
    title: '【回放】音乐演唱会',
    cover: 'https://picsum.photos/seed/live3/400/300',
    url: 'https://media.w3.org/2010/05/bunny/movie.mp4',
    uploader: '音乐频道',
    avatar: 'https://picsum.photos/seed/avatar3/100/100',
    views: 98765,
    danmaku: 9876,
    time: '2023-11-18 20:00',
    type: 'replay',
    desc: '精彩音乐演唱会回放',
    category: '音乐',
    tags: ['音乐', '演唱会', '回放'],
    location: '广州',
  },
]

// 处理 DeepSeek 请求
app.post('/api/deepseek', async (req, res) => {
  try {
    console.log('Received request body:', req.body)

    // 设置 SSE 相关的响应头
    res.setHeader('Content-Type', 'text/event-stream')
    res.setHeader('Cache-Control', 'no-cache')
    res.setHeader('Connection', 'keep-alive')
    res.setHeader('X-Accel-Buffering', 'no') // 禁用 Nginx 缓冲

    // 发送初始连接成功消息
    res.write('data: {"content": "连接成功"}\n\n')

    const completion = await openai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'system',
          content: '你是一个有帮助的AI助手。',
        },
        ...req.body.messages,
      ],
      temperature: 0.7,
      max_tokens: 1000,
      top_p: 0.95,
      frequency_penalty: 0,
      presence_penalty: 0,
      stream: true,
    })

    // 使用 try-catch 包装每个数据块的处理
    for await (const chunk of completion) {
      try {
        const content = chunk.choices[0]?.delta?.content || ''
        if (content) {
          const data = JSON.stringify({ content })
          // 确保每个消息都有正确的格式：data: {...}\n\n
          res.write(`data: ${data}\n\n`)
          // 立即刷新数据
          if (res.flush) res.flush()
        }
      } catch (e) {
        console.error('Error processing chunk:', e)
        // 发送错误消息
        res.write(`data: ${JSON.stringify({ error: true, message: e.message })}\n\n`)
      }
    }

    // 发送结束标记
    res.write(`data: {"done":true}\n\n`)
    res.end()
  } catch (error) {
    console.error('API Error:', {
      name: error.name,
      status: error.status,
      message: error.message,
      type: error.type,
    })

    // 发送错误消息
    const errorData = JSON.stringify({
      error: true,
      message: error.message || 'Unknown error',
    })
    res.write(`data: ${errorData}\n\n`)
    res.end()
  }
})

// 登录接口
app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body

  const user = users.find((u) => u.username === username)
  if (!user || user.password !== password) {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误',
    })
    return
  }

  // 生成 token (实际项目中应该使用 JWT)
  const token = `token_${Math.random().toString(36).slice(2)}`

  res.json({
    code: 0,
    data: {
      token,
      refreshToken: `refresh_${token}`,
    },
    message: '登录成功',
  })
})

// 获取用户信息接口
app.get('/api/user/info', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1]
  if (!token) {
    res.status(401).json({
      code: 401,
      message: '未登录',
    })
    return
  }

  // 模拟返回用户信息
  res.json({
    code: 0,
    data: {
      id: 1,
      name: '管理员',
      avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
    },
    message: 'ok',
  })
})

// 退出登录接口
app.post('/api/auth/logout', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1]
  if (!token) {
    res.status(401).json({
      code: 401,
      message: '未登录',
    })
    return
  }

  // 实际项目中，这里可能需要:
  // 1. 将 token 加入黑名单
  // 2. 清除服务端 session
  // 3. 记录退出日志等

  res.json({
    code: 0,
    data: null,
    message: '退出成功',
  })
})

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: 'Server is working!' })
})

// 修改朋友圈分页接口
app.get('/api/moments', (req, res) => {
  const page = parseInt(req.query.page) || 1
  const pageSize = parseInt(req.query.pageSize) || 10
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const total = moments.length

  const data = moments.slice(start, end)

  // 修改返回格式，确保 hasMore 计算正确
  res.json({
    code: 0,
    data: {
      list: data,
      pagination: {
        page,
        pageSize,
        total,
        hasMore: end < total, // 修改这里的判断逻辑
      },
    },
    message: 'success',
  })
})

// 获取直播列表
app.get('/api/video/live/list', (req, res) => {
  const { page = 1, size = 10, category } = req.query
  const start = (Number(page) - 1) * Number(size)
  const end = start + Number(size)

  let filteredList = videoList
  if (category) {
    filteredList = videoList.filter((video) => video.category === category)
  }

  const list = filteredList.slice(start, end)

  res.json({
    code: 0,
    data: {
      list,
      total: filteredList.length,
      hasMore: end < filteredList.length,
    },
    message: 'success',
  })
})

// 获取附近直播列表
app.get('/api/video/live/nearby', (req, res) => {
  const { page = 1, size = 10 } = req.query
  const start = (Number(page) - 1) * Number(size)
  const end = start + Number(size)

  // 模拟添加距离信息
  const nearbyList = videoList.map((video) => ({
    ...video,
    distance: Math.floor(Math.random() * 10000), // 随机距离 0-10km
  }))

  // 按距离排序
  nearbyList.sort((a, b) => (a.distance || 0) - (b.distance || 0))

  const list = nearbyList.slice(start, end)

  res.json({
    code: 0,
    data: {
      list,
      total: nearbyList.length,
      hasMore: end < nearbyList.length,
    },
    message: 'success',
  })
})

// 获取视频详情
app.get('/api/video/detail/:id', (req, res) => {
  const { id } = req.params
  const video = videoList.find((v) => v.id.toString() === id)

  if (video) {
    res.json({
      code: 0,
      data: video,
      message: 'success',
    })
  } else {
    res.status(404).json({
      code: 404,
      message: '视频不存在',
    })
  }
})

// 获取视频分类
app.get('/api/video/categories', (req, res) => {
  const categories = [
    { id: 1, name: '游戏', icon: 'game-o' },
    { id: 2, name: '音乐', icon: 'music-o' },
    { id: 3, name: '舞蹈', icon: 'smile-o' },
    { id: 4, name: '知识', icon: 'book' },
    { id: 5, name: '生活', icon: 'gift-o' },
    { id: 6, name: '美食', icon: 'food-o' },
    { id: 7, name: '动物', icon: 'cat-o' },
    { id: 8, name: '更多', icon: 'apps-o' },
  ]

  res.json({
    code: 0,
    data: {
      list: categories,
      total: categories.length,
      hasMore: false,
    },
    message: 'success',
  })
})

// 获取分类下的视频列表
app.get('/api/video/category/:category', (req, res) => {
  const { category } = req.params
  const { page = 1, size = 10 } = req.query
  const start = (Number(page) - 1) * Number(size)
  const end = start + Number(size)

  const filteredList = videoList.filter((video) => video.category === category)
  const list = filteredList.slice(start, end)

  res.json({
    code: 0,
    data: {
      list,
      total: filteredList.length,
      hasMore: end < filteredList.length,
    },
    message: 'success',
  })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`)
})
